package pl.auction_search.search;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SearchHelper {
	private static final String ISEARCHER_ID = "pl.auction_search.search";

	// TODO Query instead of String;
	/**public static void executeSearchWithRegisteredExtensions(Query.. 
	 * @return 
	 * @throws CoreException */
	public static List<ISearcher> listRegisteredSearchers() {
		try {
			final List<ISearcher> searchers = new LinkedList<ISearcher>();
			IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(ISEARCHER_ID);
			for (IConfigurationElement e : config) {
				final Object o = e.createExecutableExtension("class");
				if (o instanceof ISearcher) {
					searchers.add((ISearcher) o);
				}
			}
			return searchers;
		} catch (CoreException e) {
			handleException(e);
			return null;
		}
	}

	public static void handleException(final Throwable ex) {
		Display.getDefault().asyncExec(new Runnable() {
			@Override public void run() {
				Shell[] shells = Display.getDefault().getShells();
				if (shells == null || shells.length == 0) {
					ex.printStackTrace();
				} else {
					IStatus status = new Status(IStatus.ERROR, pl.auction_search.Activator.PLUGIN_ID, 0,
							"Could not perform requested action.", ex);
					ErrorDialog.openError(shells[0], "Error", null, status);
				}
			}}
		);
	}

	/**
	 * check if collection is empty
	 **/
	public static boolean isEmpty(Collection<?> l) {
		return l == null || 0 == l.size();
	}
}
